import uCharts from '../../utils/u-charts';
var _self;
var canvaColumn = null;
const db = wx.cloud.database()
Page({
  data: {
    cWidth: '',
    cHeight: '',
    radio: '2',
    radios: '2',
    expenditure2: "",
    income2: "",
    option1: [{
        text: '出库',
        value: '1'
      },
      {
        text: '进仓',
        value: '2'
      },

    ],
    option2: [{
        text: '饼状图',
        value: '1'
      },
      {
        text: '折线图',
        value: '2'
      },

    ],
    loading_id: 0
  },
  onChange(event) {
    console.log(event)
    this.setData({
      radio: event.detail,
      loading_id: 0
    });
    let that = this
    wx.cloud.callFunction({
      name: 'getlist',
      success: function (res) {
        let mouthdata = res.result.filter(e => {
          return e.date.slice(0, 7) == that.formatDatenouth(new Date())
        }).sort(function (a, b) {
          return Date.parse(a.date) - Date.parse(b.date);
        }).filter(e => {
          return e.userid == wx.getStorageSync('id')
        })
        //获取支出和收入的详细数据
        let income = mouthdata.filter(e => {
          return e.money > 0
        })
        let expenditure = mouthdata.filter(e => {
          return that.data.radio == '1' ? e.money < 0 : e.money > 0
        })

        let expendituredata = []
        expenditure.forEach(e => {
          expendituredata.push({
            name: e.recordtype,
            data: that.data.radio == '1' ? -e.money : e.money,
            date: e.date.substring(e.date.length - 2)
          })
        })
        console.log(expendituredata)
        let obj = {}
        let objs = {}
        for (let i = 0; i < expendituredata.length; i++) {
          var item = expendituredata[i].name // a为计算的属性,可换成b,c
          var items = expendituredata[i].data
          if (obj[item]) {
            obj[item].push(items)
          } else {
            obj[item] = []
            obj[item].push(items)
          }
        }
        // 获取当月 某天的 支出金额
        for (let x = 0; x < expendituredata.length; x++) {
          var itemss = expendituredata[x].date
          var itema = expendituredata[x].data
          if (objs[itemss]) {
            objs[itemss].push(itema)
          } else {
            objs[itemss] = []
            objs[itemss].push(itema)
          }
        }
        console.log(objs)
        let list = []
        let lists = []
        Object.keys(obj).forEach(function (key) {
          let num = 0
          obj[key].forEach(e => {
            num = num + e
          })
          list.push({
            name: key,
            data: num
          })

        });
        Object.keys(objs).forEach(function (key) {
          let num = 0
          objs[key].forEach(e => {
            num = num + e
          })
          lists.push({
            name: key,
            data: num
          })

        });
        let categoriesdata = []
        let seriesdata = []
        lists.forEach(e => {
          categoriesdata.push(e.name)
          seriesdata.push(e.data)
        })
        console.log(lists)
        let Column = {
          categories: [],
          series: []
        };
        Column.series = list;
        //自定义标签颜色和字体大小
        // Column.series[1].textColor = 'red';
        // Column.series[1].textSize = 18;
        _self.showColumn("canvasColumn", Column);
        let datalists = {
          categories: categoriesdata,
          series: [{
            name: that.data.radio == '1' ? '支出' : '收入',
            data: seriesdata
          }]
        }
        _self.showColumns("canvasColumns", datalists);
        that.setData({
          loading_id: 1
        });
      },
      fail: console.error
    })
  },
  
  onChanges(event) {
    this.setData({
      radios: event.detail,
    });
  },
  onShow() {
    if (typeof this.getTabBar === 'function' &&
    this.getTabBar()) {
    
    this.getTabBar().setData({
    id: 3
    })}
    _self = this;
    let that = this
    this.setData({
      radio: '2',
      radios: '1',
      loading_id: 0
    });
    wx.cloud.callFunction({
      name: 'getlist',
      success: function (res) {
        let mouthdata = res.result.filter(e => {
          return e.date.slice(0, 7) == that.formatDatenouth(new Date())
        }).sort(function (a, b) {
          return Date.parse(a.date) - Date.parse(b.date);
        }).filter(e => {
          return e.userid == wx.getStorageSync('id')
        })
        //获取支出和收入的详细数据
        let income = mouthdata.filter(e => {
          return e.money > 0
        })
        let expenditure = mouthdata.filter(e => {
          return that.data.radio == '1' ? e.money < 0 : e.money > 0
        })

        let expendituredata = []
        expenditure.forEach(e => {
          expendituredata.push({
            name: e.recordtype,
            data: that.data.radio == '1' ? -e.money : e.money,
            date: e.date.substring(e.date.length - 2)
          })
        })
        console.log(expendituredata)
        let obj = {}
        let objs = {}
        for (let i = 0; i < expendituredata.length; i++) {
          var item = expendituredata[i].name // a为计算的属性,可换成b,c
          var items = expendituredata[i].data
          if (obj[item]) {
            obj[item].push(items)
          } else {
            obj[item] = []
            obj[item].push(items)
          }
        }
        // 获取当月 某天的 支出金额
        for (let x = 0; x < expendituredata.length; x++) {
          var itemss = expendituredata[x].date
          var itema = expendituredata[x].data
          if (objs[itemss]) {
            objs[itemss].push(itema)
          } else {
            objs[itemss] = []
            objs[itemss].push(itema)
          }
        }
        console.log(objs)
        let list = []
        let lists = []
        Object.keys(obj).forEach(function (key) {
          let num = 0
          obj[key].forEach(e => {
            num = num + e
          })
          list.push({
            name: key,
            data: num
          })

        });
        Object.keys(objs).forEach(function (key) {
          let num = 0
          objs[key].forEach(e => {
            num = num + e
          })
          lists.push({
            name: key,
            data: num
          })

        });
        let categoriesdata = []
        let seriesdata = []
        lists.forEach(e => {
          categoriesdata.push(e.name)
          seriesdata.push(e.data)
        })
        console.log(lists)
        let Column = {
          categories: [],
          series: []
        };
        Column.series = list;
        //自定义标签颜色和字体大小
        // Column.series[1].textColor = 'red';
        // Column.series[1].textSize = 18;
        _self.showColumn("canvasColumn", Column);
        let datalists = {
          categories: categoriesdata,
          series: [{
            name: that.data.radio == '1' ? '支出' : '收入',
            data: seriesdata
          }]
        }
        _self.showColumns("canvasColumns", datalists);
        that.setData({
          loading_id: 1
        });
      },
      fail: console.error
    })
  },
  onLoad: function () {
    _self = this;
    this.cWidth = wx.getSystemInfoSync().windowWidth;
    this.cHeight = 500 / 750 * wx.getSystemInfoSync().windowWidth;
    this.getServerData();
  },
  getServerData: function () {

    // api.fetchApi('/crp/dayhoursbyid/', { id: wx.getStorageSync('userid') }, 'GET').then(res => {
    //   console.log()
    //   let datalist = res.data.data.sort(function (a, b) {
    //     return Date.parse(b.workdate) - Date.parse(a.workdate);
    //   }).slice(0, 5)
    //   let datelist = []
    //   let stydylist = []
    //   let deplist = []
    //   datalist.forEach(e =>{
    //     datelist.push(e.workdate.slice(5))
    //     stydylist.push(e.studyhours)
    //     deplist.push(e.dephours)
    //   })
    //   let Column = { categories: [], series: [] };
    //   Column.categories = datelist;
    //   Column.series = [{name:'项目工时',data:stydylist},{name:'部门工时',data:deplist}];
    //   //自定义标签颜色和字体大小
    //   // Column.series[1].textColor = 'red';
    //   // Column.series[1].textSize = 18;
    //   _self.showColumn("canvasColumn", Column);

    // })

  },
  showColumn(canvasId, chartData) {
    console.log(chartData.series,)
    canvaColumn = new uCharts({
      $this:this,
      canvasId: canvasId,
      type: 'pie',
      fontSize:12,
      background:'#FFFFFF',
      pixelRatio:1,
      series: chartData.series,
      animation: true,
      width: this.cWidth,
      height: this.cHeight,
      dataLabel: true,
      extra: {
        pie: {
          labelWidth:18
        }
      },
    });

  },
  showColumns(canvasId, chartData) {
    canvaColumn = new uCharts({
      $this: _self,
      canvasId: canvasId,
      type: 'line',
      legend: true,
      fontSize: 11,
      background: '#FFFFFF',
      pixelRatio: 1,
      animation: true,
      categories: chartData.categories,
      series: chartData.series,
      xAxis: {
        // rotateLabel: true,
        labelCount: 15
      },
      yAxis: {
        //disabled:true
      },
      dataLabel: true,
      width: _self.cWidth,
      height: _self.cHeight,
      extra: {
        line: {
          type: 'straight'
        }
      }
    });

  },
  tz(){
    wx.reLaunch({
      url: '../record/record',
    })
  },
  touchColumn(e) {
    console.log(e)
    canvaColumn.showToolTip(e, {
      format: function (item, category) {
        if (typeof item.data === 'object') {
          return item.name + ':' + item.data.value
        } else {
          return item.name + ':' + item.data
        }
      }
    });
  },
  touchColumns(e) {
    canvaColumn.showToolTip(e, {
      format: function (item, category) {
        if (typeof item.data === 'object') {
          return item.name + ':' + item.data.value
        } else {
          return item.name + ':' + item.data
        }
      }
    });
  },
  formatDatenouth(date) {
    const dt = new Date(date);
    const y = dt.getFullYear();
    const m = (dt.getMonth() + 1 + "").padStart(2, "0");
    return `${y}-${m}`;
  },
})